package net.chrone.quickpayapi.service.impl;


import net.chrone.quickpayapi.mapper.SeqMapper;
import net.chrone.quickpayapi.model.Seq;
import net.chrone.quickpayapi.service.SeqService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service(value="seqService")
public class SeqServiceImpl implements SeqService {
	
	@Autowired
	private SeqMapper seqMapper;
	
	@Transactional
	public String updateAndGetSequence(String id,int length) {
		long num = 0;
        try {        	
        	int row = seqMapper.tickCountSeq(id);
        	if (row==0) {
        		Seq seq = new Seq();
        		seq.setId(id);
        		seq.setSeq(num);
        		try{
        		    seqMapper.insertSelective(seq);
        		}catch(Exception e){
        		    return "-1";
        		}
        		num = 0;
        	} else {
        		Seq seq = seqMapper.selectByPrimaryKey(id);
        		num = seq.getSeq();
        		if(num > 999999998){ //数据超长归零处理
        			seq.setSeq(0L);
        			seqMapper.updateByPrimaryKeySelective(seq);
        		}
        	}
        }catch (Exception e) {
        	e.printStackTrace();
		}
       return format(num, length);
	}
	
	public String format(long num, int length) {
		if (num<0) return "";
		StringBuffer sb = new StringBuffer();
		String s = ""+num;
		if (s.length()<length) {
			int addNum = length-s.length();
			for (int i=0;i<addNum;i++) {
				sb.append("0");
			}
			sb.append(s);
		} else {
			return s.substring(s.length()-length,s.length());
		}
		return sb.toString();
	}

}
